#include <iostream>
#include <mutex>

// 饿汉模式
class eagerSingleton
{
public:
    static eagerSingleton *getObject()
    {
        return _pinst;
    }

private:
    eagerSingleton() {}
    eagerSingleton(eagerSingleton &) = delete;
    eagerSingleton &operator=(eagerSingleton &) = delete;

private:
    // 唯一静态对象
    static eagerSingleton *_pinst;
};
// 类外提前初始化
eagerSingleton *eagerSingleton::_pinst = new eagerSingleton();

// 懒汉模式
std::mutex lock;
class lazySingleton
{
public:
    static lazySingleton *getObject()
    {
        // 只有为空的时候才进行初始化

        if (_pinst == nullptr)
        {
            {
                std::unique_lock<std::mutex> ul(lock);
                if (_pinst == nullptr)
                    _pinst = new lazySingleton();
            }
        }

        return _pinst;
    }

private:
    lazySingleton() {}
    lazySingleton(lazySingleton &) = delete;
    lazySingleton &operator=(lazySingleton &) = delete;

private:
    // 唯一静态对象
    static lazySingleton *_pinst;
};

// 利用C++11新特性：保证局部静态变量的初始化是线程安全的
class mordenSingleton
{
public:
    mordenSingleton &getObject()
    {
        // 这里C++11直接保证初始化是线程安全的
        static mordenSingleton _pinst;
        return _pinst;
    }

private:
    mordenSingleton() {}
    mordenSingleton(mordenSingleton &) = delete;
    mordenSingleton &operator=(mordenSingleton &) = delete;
};